<template>
  <div class="h-full flex flex-col">
    <a-card class="-mt-2 -mx-2 mb-2" :body-style="{ padding: '4px 0' }">
      <a-tabs v-model:activeKey="activeKey" hide-add type="editable-card" @edit="onRemove" @tab-click="onTabClick">
        <a-tab-pane v-for="pane in appStore.keepAliveRouters" :key="pane.key" :tab="pane.title" :closable="appStore.keepAliveRouters.length !== 1" />
      </a-tabs>
    </a-card>
    <div class="flex-1">
      <router-view v-slot="{ Component }">
        <keep-alive>
          <component :is="Component" />
        </keep-alive>
      </router-view>
    </div>
  </div>
</template>
<script setup>
import { ref, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import useAppStore from '@/store/app'

const appStore = useAppStore()

const router = useRouter()
const activeKey = ref()
const isShow = ref(true)

const onRemove = (key, action) => {
  if (action === 'remove') {
    const index = appStore.keepAliveRouters.findIndex((pane) => pane.key === key)
    const { path } = router.currentRoute.value
    appStore.keepAliveRouters.splice(index, 1)
    if (path === key) {
      const { key } = appStore.keepAliveRouters[0]
      router.push(key)
    }
  }
}
const onTabClick = (willPath) => {
  const { path } = router.currentRoute.value
  willPath === path ? reloadPage() : router.push(willPath)
}
const reloadPage = () => {
  isShow.value = false
  nextTick(() => {
    isShow.value = true
  })
}
const addPanes = () => {
  const { path, meta } = router.currentRoute.value
  activeKey.value = path
  const isExist = appStore.keepAliveRouters.some((pane) => pane.key === path)
  if (!isExist && meta.tabName) {
    appStore.keepAliveRouters.push({ key: path, title: meta.tabName })
  }
}
watch(
  () => router.currentRoute.value,
  () => {
    addPanes()
  },
  { immediate: true }
)
</script>
<style lang="less" scoped>
:deep(.ant-tabs-nav) {
  padding-left: 16px;
  .ant-tabs-tab {
    border-bottom-color: transparent;
    .ant-tabs-tab-remove {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 24px;
      height: 24px;
      padding: 0;
      .anticon {
        margin-left: 10px;
        color: #7c7c7c90;
        :hover {
          padding: 1px;
          color: var(--primary-color);
          background-color: var(--secondary-color);
          border-radius: 100%;
        }
      }
    }
  }
}
</style>
